import { createStore } from 'vuex'
import {USERNAME,PREFIX,IDENT,EQUAL,EXPIRES} from '@/utils/currency.js'
import api from '@/api/index.js'
const Base64 = require("js-base64").Base64//引入加密方式
// import request from '@/utils/request.js'
import router from '@/router/index.js'
const store=createStore({
    state(){
        return {
            hasLogin: localStorage.getItem('hasLogin'),
            // userNickname:'',
            // userAvator:'',
            userInfo:{
            },
            roleName:'',
            STORAGEITEM:{

            },
            // tabbar_index:0,
            TOKEN:'',
            default_url:'/userAdmin'
        }
    },
    mutations:{
        setUserInfo(state, params){//设置state
            var userinfo = state.userinfo;
            for (let prop in params){
                // if (params[prop]){
                    userinfo[prop] = params[prop]
                    localStorage.setItem(prop, params[prop]);//保存缓存
                // }
            }
            localStorage.setItem('hasLogin', 1);//保存登录标识
            state.hasLogin = 1;
            console.log(state.userinfo)
        },
        setStorage(state,params){//只存基本用户信息
        },
        signout(state){//登出
            //删除cookie
            //账号
            let cookie_username=Base64.encode(USERNAME)+IDENT + EQUAL;
            this.commit('clearCookie',{
              cname:cookie_username,
              cvalue:'',
              exdays:'-1'
            })
            //密码
            let cookie_password=Base64.encode(PREFIX)+IDENT + EQUAL;
            this.commit('clearCookie',{
              cname:cookie_password,
              cvalue:'',
              exdays:'-1'
            })
        },
        clearCookie(state,params){
          let {cname, cvalue, exdays}=params
          var d = new Date();
          d.setTime(d.getTime() + (exdays*24*60*60*1000));
          var expires = "expires="+d.toUTCString();
          document.cookie = cname  + cvalue + "; " + expires;
        },
        toIndex(state){//跳转到首页
            router.replace('/')
            // location.reload();
        },
        toLogin(state){
            router.replace('/login')
        },
        setToken(state,data){//授权码
            state.TOKEN =data;
            localStorage.setItem('TOKEN', data);
        },
        setRole(state,data){//保存角色id
            localStorage.setItem('role_id', data);
        },
        parsrRole(state){
            var str='业务员'
            var roleType=state.userinfo.roleType
            if (roleType == 'Photographer' || roleType=='photographer'){
                str = '摄影师'
            }
            else if (roleType == 'UI'){
                str = 'UI设计师'
            }
            state.roleName= str
        }
    },
    actions:{
        //检查登录状态
        async checkLogin(context,params=null){
            console.log('start checkLogin....');
            let toIndex=false,token="";
            try{
              const res=await context.dispatch("getCookie");
              const localStorage_token = localStorage.getItem('TOKEN');
              if(res.status==1 && localStorage_token){
                  token=localStorage_token;
                  toIndex=true;
              }
            }
            catch(error){
              console.log(error);
            }
            if(params?.type == 'get') {
                var loginState = -1
                if(toIndex) {
                    loginState=1
                }
                return loginState
            }
            else{
                if(toIndex){
                  context.commit("setToken",token)
                  context.state.token = token;//赋值token
                  context.commit('toIndex');//跳转首页
                }
                else{
                  router.replace('/login');//跳转登录页
                }
            }
            
        },
        // 获取cookie
        getCookie(context) {
          return new Promise((resolve,reject)=>{
            var flag=false,userInfo={};
            if (document.cookie.length > 0) {
               //分割成一个个独立的“key=value”的形式
               let arr = document.cookie.split("; ");
               // console.log(document.cookie);
               for (let i = 0; i < arr.length; i++) {
                 // 再次切割，arr2[0]为key值，arr2[1]为对应的value
                 let arr2 = arr[i].split(EQUAL);
                 if(arr2.length>0){
                     //解码=====
                     if(arr2[0].includes(IDENT)){
                       var field= arr2[0].split(IDENT)[0];
                       let plain_text=Base64.decode(field)
                       if(arr2[1]){
                         if(plain_text === PREFIX){//密码
                           userInfo.password = Base64.decode(arr2[1]);// base64解密
                         }
                         else if(plain_text === USERNAME){//账号
                           userInfo.username = Base64.decode(arr2[1]);// base64解密
                         }
                         flag=true
                       }
                     }
                 }
               }
            }
            if(!flag){
               reject({
                  status:'-1'
               })
            }
            else{
              resolve({
                 status:"1",
                 userInfo
              })
            }
          })
        },
        //登录
        toLogin:(context,params)=>api.login({
          password:params.password,
          username:params.username,
          type:'password',
          identity:'admin'
        }),
        setCookie(context,params) { // 加密设置cookie
          return new Promise((resolve,reject)=>{
             let {password,username} = params;
             let date = new Date(); // 获取时间
             date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * EXPIRES); // 保存的天数
             // 字符串拼接cookie
             window.document.cookie = Base64.encode(USERNAME)+IDENT + EQUAL + username + ";path=/;expires=" + date.toGMTString();
             window.document.cookie = Base64.encode(PREFIX)+IDENT+ EQUAL + password + ";path=/;expires=" + date.toGMTString();
             resolve({
               status:1
             })
          })
 	     },
    }

})
export default store
